package org.lonetree.tc.webapp.actions;

import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Book;
import org.lonetree.tc.core.Book.Isbn;
import org.lonetree.tc.core.dao.BookDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.core.search.BookCriteria;
import org.lonetree.tc.webapp.forms.BookForm;

public class SearchBook extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
            
            try{
            	
                DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
                BookDAO bdao = factory.getBookDAO();
                BookCriteria criteria=new BookCriteria();
                String s=request.getMethod();
              
    	
                String isbn = request.getParameter("isbn"); 
            	if (isbn != null && !isbn.trim().equals(""))
            	{
            		criteria.setIsbn(new Isbn(isbn));
                    Set<Book> results=bdao.findBooks(criteria);
                    request.setAttribute("books", results);
                    return mapping.findForward("success");  
            	}
            	else//no isbn, then must have title.otherwise, exception
            	{
            		String title = request.getParameter("title"); 
            		if (title != null && !title.trim().equals(""))
            		{
            			criteria.setTitle(title);
            			Set<Book> results=bdao.findBooks(criteria);
            			request.setAttribute("books", results);
            			return mapping.findForward("success");
            		}
            		//if no isbn or title, then it is wrong.
            		return mapping.findForward("failure");
            	}           	
            }
            catch (Exception e)
            {
                return mapping.findForward("failure");
            }
	}

}
